package cn.cnsy123.shorturls.business.encoder;

import java.security.SecureRandom;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PasswordEncoder {
    
    private static final Logger logger = LoggerFactory.getLogger(PasswordEncoder.class);
    
    private Pattern BCRYPT_PATTERN = Pattern
            .compile("\\A\\$2(a|y|b)?\\$(\\d\\d)\\$[./0-9A-Za-z]{53}");
    private final int strength;
    private final BCryptVersion version;

    private final SecureRandom random;
    
    public PasswordEncoder() {
        this(-1);
    }
    
    public PasswordEncoder(int strength) {
        this(strength, null);
    }
    
    public PasswordEncoder(BCryptVersion version) {
        this(version, null);
    }
    
    public PasswordEncoder(BCryptVersion version, SecureRandom random) {
        this(version, -1, random);
    }
    
    public PasswordEncoder(int strength, SecureRandom random) {
        this(BCryptVersion.$2A, strength, random);
    }
    
    public PasswordEncoder(BCryptVersion version, int strength) {
        this(version, strength, null);
    }
    
    public PasswordEncoder(BCryptVersion version, int strength, SecureRandom random) {
        if (strength != -1 && (strength < BCrypt.MIN_LOG_ROUNDS || strength > BCrypt.MAX_LOG_ROUNDS)) {
            throw new IllegalArgumentException("Bad strength");
        }
        this.version = version;
        this.strength = strength == -1 ? 10 : strength;
        this.random = random;
    }

    public String encode(CharSequence rawPassword) {
        String salt;
        if (random != null) {
            salt = BCrypt.gensalt(version.getVersion(), strength, random);
        } else {
            salt = BCrypt.gensalt(version.getVersion(), strength);
        }
        return BCrypt.hashpw(rawPassword.toString(), salt);
    }
    
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (encodedPassword == null || encodedPassword.length() == 0) {
            logger.warn("Empty encoded password");
            return false;
        }

        if (!BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
            logger.warn("Encoded password does not look like BCrypt");
            return false;
        }

        return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
    }
    
    public enum BCryptVersion {
        $2A("$2a"),
        $2Y("$2y"),
        $2B("$2b");

        private final String version;

        BCryptVersion(String version) {
            this.version = version;
        }

        public String getVersion() {
            return this.version;
        }
    }
}
